package com.xxx.springboot.util;

import java.util.Random;
import java.util.HashSet;
import java.util.Set;

/**
 * ID生成器
 */
public class UIDGenerator {
	
    private static final char chars[] = {
    			'J', '4', 'B', 'X', 'E', 'V', 'F', 'G', 'W', 'I', 
    			'A', 'K', '7', '5', 'N', 'P', 'Q', 'R', 'S', '3',
    			'U', '1', 'C', '2', 'T', '6', 'H', 'Y', '8', 'M', 'L', 'D'};
 
	/**
	 * 生成10位用户ID
	 */
	public static String generateUserId() {
		Random r = new Random();
        StringBuffer sb = new StringBuffer(10);
        for (int j = 1; j <= 10; j++) {
            int i = r.nextInt(10);
            if (j == 1 || (j >= 8 && j <= 10)) {
                while (i == 0) {
                    i = r.nextInt(10);
                }
            }
            sb.append(i);
        }
        return sb.toString();
	}
	
	/**
	 * 根据userId生成邀请码
	 */
	public static String generateInviteCode(String userId) {
		long id = Long.valueOf(userId);
		char[] a = new char[6];
        for (int i = 0; i < a.length; i++) {
            int pow = (int) Math.pow(chars.length, i);
            a[i] = charAtStuff((int) (id / pow % chars.length) + i);
        }
        return String.valueOf(a);
	}
	
    private static char charAtStuff(int index) {
        return index < chars.length ? chars[index] : chars[index - chars.length];
    }
    
    /**
     * main
     * @param args
     */
	public static void main(String[] args) {
		Set<String> userIdSet = new HashSet<>();
		Set<String> inviteCodeSet = new HashSet<>();
		for(int i=0; i<1000000; i++) {
			String userId = generateUserId();
			String inviteCode = generateInviteCode(userId);
			System.out.println(i + " userId:" + userId + "\t inviteCode:" + inviteCode);
			userIdSet.add(userId);
			inviteCodeSet.add(inviteCode);
			if(userId.startsWith("0")) {
				break;
			}
		}
		System.out.println("userIdSet.size:" + userIdSet.size());
		System.out.println("inviteCodeSet.size:" + inviteCodeSet.size());
	}
}
